<template>
  <div v-for="item in data" :key="item.id" class="realtimemonito-menu">
    <div
      class="menu__header"
      @click="commEvent.onClickMenu(item)"
      :style="{ paddingLeft: `${item.level * 10 + 10}px` }"
      :class="{ 'header-active': menuId === item.id }"
    >
      <el-icon
        v-if="item?.children && item.children.length > 0"
        class="header__icon"
        :class="{ 'icon--active': openId.includes(item.id) }"
      >
        <CaretRight />
      </el-icon>
      {{ item.text }}
    </div>
    <div
      v-if="item?.children && item.children.length > 0"
      class="menu__list"
      :class="{ 'menu--active': openId.includes(item.id) }"
    >
      <div class="list__container">
        <realtimemonito-menu :data="item.children" :menu-id="menuId" :open-id="openId" @menu-click="commEvent.onClickMenu" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { PropType } from "vue"
export type MenuType = {
  id: number
  text: string
  level: number
  pid?: number
  pidArr?: number[]
  children?: MenuType[]
}
defineProps({
  data: { type: Array as PropType<MenuType[]>, default: () => [] },
  menuId: { type: Number, default: () => -1 },
  openId: { type: Array as PropType<Array<number>>, default: () => [] }
})
const emit = defineEmits(["update:openId", "update:menuId", "menuClick"])
const commEvent = {
  onClickMenu: (item: any) => {
    emit("menuClick", item)
    emit("update:menuId", item.id)
    // 设置展开节点id
    if (item?.children && item.children.length > 0) {
      let _openId: number[] = []
      if (item?.pidArr) {
        _openId = [...item.pidArr, item.id]
      } else {
        _openId = [item.id]
      }
      emit("update:openId", _openId)
    }
  }
}
</script>

<style lang="scss" scoped>
.realtimemonito-menu {
  box-sizing: border-box;
  .menu__header {
    box-sizing: border-box;
    width: 100%;
    padding: 5px 0;
    font-size: 14px;
    cursor: pointer;
    user-select: none;
    &.header-active {
      color: #ffffff;
      background-color: var(--el-color-primary);
    }
    &:not(.header-active):hover {
      background-color: var(--el-color-primary-light-9);
    }
    .header__icon {
      color: var(--el-color-primary);
      transition: all 0.3s;
    }
    .icon--active {
      transform: rotate(90deg);
    }
  }
  .menu__list {
    display: grid;
    grid-template-rows: 0fr;
    width: 100%;
    transition: all 0.3s;
    .list__container {
      overflow: hidden;
    }
    &.menu--active {
      grid-template-rows: 1fr;
    }
  }
}
</style>
